<template>
  <div class="proStirage">
    <div style="display: flex">
      <jc-button
        :btn-arr="['reload', 'sub', 'remove', 'option', 'push', 'pass', !list.length && 'check', 'batchFill']"
        :disab-arr="['close', 'cancel', 'using', 'freeze']"
        :fbillno="fbiVal"
        url="tPrdInstock/getPrdInStockList"
        @save="save"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @submit="submit(1)"
        @noSubmit="submit(2)"
        @refresh="handleGetUntreated"
        @del="proAudit"
        @toExcel="handleExport"
        @handleCom1="printing(1)"
        @handleCom2="printing(2)"
        @check="check('up')"
        @check1="check('down')"
        @pushDown="pushDown"
      />
    </div>
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button
          type="primary"
          class="btn"
          size="mini"
          @click="handleQuerySonClass"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        table-selection
        sortable
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="pushDetail"
      >
        <!--        单据编号-->
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="pushDetail(col.scope.row)">
            {{ col.scope.row.fmobillNo }}
          </el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <template v-slot:btnSlot="col">
          <el-tag v-if="col.scope.row.fisconfirm===0" type="primary">
            {{ $t('market.unconfirmed') }}
          </el-tag>
          <el-tag v-else type="success">{{ $t('market.confirmed') }}</el-tag>
        </template>
        <!--        审核状态-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentstatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">
            {{ col.scope.row.fdocumentstatus }}
          </el-tag>
        </template>
        <!-- 实际人工 -->
        <template v-slot:btnStates="col">
          <el-input-number
            v-model="col.scope.row.realWagesprice"
            size="mini"
            :disabled="col.scope.row.fisconfirm===1"
            @change="wagesHeadel(col.scope.$index)"
          />
        </template>
        <!--报工金额===金额 ? 绿色 : 黄色-->
        <template v-slot:billSlot="col">
          <span v-if="col.scope.row.realWages===col.scope.row.fsumprice" style="color: #67c23a;">{{ col.scope.row.fsumprice }}</span>
          <span v-else style="color: #E6A23C;">{{ col.scope.row.fsumprice }}</span>
        </template>
      </jc-table>
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <!--下推-->
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
            :disabled="item.fid===185||item.fid===186"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  SelectSCRK,
  updateRealWagesprice,
  updateFisconfirmStatus,
  insertProcess,
  auditPrdMos,
  unauditPrdMos, submitPrdMos, unsubmitPrdMos, delPrdMos
} from '@/api/production/productionList'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import { toMxBmina } from '@/components/ToMxamineState'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'

export default {
  name: 'ProSupplement',
  components: {
    upDown: () => import('@/components/upDown'),
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      orderLX: this.$t('menu.workFlowOrder'),
      receipts: [this.$t('menu.workFlowOrder')], // 生产
      fbillTypeId: 184,
      convert: this.$t('market.scbjy'),
      billTypeData: [], // 采购订单单据
      isdanjuDialog: false,
      upDownVis: false,
      cha: '',
      fentryData: [],
      ftype: 61,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      proData: [],
      tableHeight: '70vh',
      fbiVal: '',
      // 表头
      tableData: [], // 生产领料数据
      tableHeader: [
        { label: this.$t('market.mobillNo'), type: 'tag', prop: 'fmobillNo', width: '120' },
        { label: this.$t('market.rkdh'), prop: 'fbillNo', width: '120px' },
        { label: this.$t('market.orderDate'), prop: 'fdate', width: '90' },
        { label: this.$t('market.workDate'), prop: 'fbgdate', width: '90' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus', width: '100' },
        { label: this.$t('market.salKhddh'), prop: 'salKhddh', width: '110' },
        { label: this.$t('market.productmodel'), prop: 'fproductmodel', width: '110' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '120px' },
        { label: this.$t('shop.fname2'), prop: 'fname', width: '110' },
        { label: this.$t('market.plaint'), prop: 'fworkshop', width: '80' },
        { label: this.$t('market.specificaTion'), prop: 'fspecificaTion', width: '100' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200px' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.realQty'), prop: 'frealQty', width: '80' },
        { label: this.$t('market.artificialPrice2'), prop: 'fprice', width: '110' },
        { label: this.$t('market.artificialAmount2'), type: 'bill', prop: 'fsumprice', width: '110' },
        { label: this.$t('market.stock2'), prop: 'fstockName', width: '120' },
        { label: this.$t('market.proOrderSeq'), prop: 'fmoentrySeq', width: '120' },
        { label: this.$t('market.pbomBillNo'), prop: 'ppbomBillNo', width: '120' },
        { label: this.$t('market.planLabor'), prop: 'realWagesprice', width: '80' }, // , type: 'states'
        { label: this.$t('market.famount'), prop: 'realWages', width: '80' },
        { label: this.$t('market.isconfirm'), type: 'btn', prop: 'fisconfirm', width: '100' },
        { label: this.$t('market.fmodel'), prop: 'fmodel', width: '100' }
      ],
      tableHeader1: []
    }
  },
  created() {
    // this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 保存
    save() {
      this.params = []
      this.val.forEach(res => {
        this.params.push({
          fid: res.fid,
          fmoentryId: res.fmoentryId,
          realWagesprice: res.realWagesprice
        })
      })
      const DATA = {
        params: this.params
      }
      updateRealWagesprice(DATA).then(res => {
        if (res.code === 0) {
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 确认 反确认
    affirm(ev) {
      this.letterConf.map(res => {
        res.fisconfirm = ev
      })
      const DATA = {
        params: this.letterConf
      }
      updateFisconfirmStatus(DATA).then(res => {
        if (res.code === 0) {
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 实际人工
    wagesHeadel(index) {
      const item = this.tableData[index]
      item.realWages = (item.frealQty * item.realWagesprice).toFixed(2)
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '生产入库列表')
        } else {
          this.startDate = ''
          this.endDate = ''
          this.searCollData.concat(this.details).forEach((res, index) => {
            if (res.field === 'startDate') {
              this.startDate = res.seach
            } else if (res.field === 'endDate') {
              this.endDate = res.seach
            }
          })
          SelectSCRK({
            startDate: this.startDate,
            endDate: this.endDate,
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                return toMxBmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '生产入库列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取生产入库列表数据
    async handleGetUntreated(ev) {
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      this.startDate = ''
      this.endDate = ''
      this.searCollData.concat(this.details).forEach((res, index) => {
        if (res.field === 'startDate') {
          this.startDate = res.seach
        } else if (res.field === 'endDate') {
          this.endDate = res.seach
        }
      })
      const DATA = {
        list: this.list,
        startDate: this.startDate,
        endDate: this.endDate,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      await SelectSCRK(DATA).then(res => {
        if (res.code === 0) {
          this.tableData = res.data.list
          this.tableData.map(item => {
            return toMxBmina(item)
          })
          this.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 详情
    pushDetail(ev) {
      const id = ev.fmobillNo
      this.$router.push({
        path: `/proOrderDetails/${id}`
      })
    },
    // 多选
    handleSelectAll(val) {
      this.fbiVal = val[0].fbillNo
      this.selectVal = []
      this.fidsData = []
      this.fentryData = []
      this.letterConf = []
      this.val = val
      val.forEach(res => {
        this.letterConf.push({
          fmoentryId: res.fmoentryid,
          fbillNo: res.fbillNo,
          realWagesprice: res.realWagesprice,
          fsumprice: res.fsumprice,
          fid: res.FID
        })
        res.fmobillNo && this.selectVal.push(res.fmobillNo)
        this.fidsData.push(res.fmoid)
        this.fentryData.push(res.fmoentryid)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审批通过
    async audit(ev) {
      const api = ev === 1 ? auditPrdMos : unauditPrdMos
      this.toExamineFun(api)
    },
    // 提交、反提交
    async submit(ev) {
      const api = ev === 1 ? submitPrdMos : unsubmitPrdMos
      this.toExamineFun(api)
    },
    // 删除
    proAudit() {
      this.$confirm('确定要删除该订单么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = delPrdMos
        this.toExamineFun(api)
      })
    },
    // 下推
    pushDown() {
      this.isdanjuDialog = true
      this.convert = this.$t('market.sczlc') // '生产订单至生产流程单'
      this.fbillTypeId = 245
      this.purpoorder1('SX_PROCESS')
    },
    // 品质检验订单单据
    async purpoorder1(ev) {
      const { data: RES } = await queryViewItem({ viewName: ev })
      this.billTypeData = RES.list
    },
    // 下推
    pushDownOrder() {
      const DATA = {
        SoucrceIds: this.fidsData,
        EntryIds: this.fentryData,
        fbillTypeId: this.fbillTypeId
      }
      insertProcess(DATA).then(res => {
        if (res.code === 0) {
          this.$router.push({
            path: `/workFlowDetail/${res.data}`
          })
          this.isdanjuDialog = false
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 上查、下查
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 套打
    printing(ev) {
      const id = this.fbiVal
      if (ev === 1) {
        this.$router.push({
          path: `/proStirTong/${id}`
        })
      } else {
        this.$router.push({
          path: `/proStirLian/${id}`
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.proStirage {
  @include listBom;
  padding: 0;
  .marL {
    margin-left: 10px;
  }
  .header {
    position: relative;
    .header-name {
      width: 100%;
      .input-width {
        width: 100px;
      }
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
